package com.infore.siteManagement.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.infore.siteManagement.dto.YunlAppInfoParam;
import com.infore.siteManagement.entity.StationAndApp;
import com.infore.siteManagement.entity.otherEntity.SysUser;
import com.infore.siteManagement.externalInterface.IdentityManagement;
import com.infore.siteManagement.outEntity.SysUserStation;
import com.infore.siteManagement.outEntity.TPlatformCustomerStation;
import com.infore.siteManagement.repository.IStationAndAppRepository;
import com.infore.siteManagement.repository.IStationRepository;
import com.infore.siteManagement.repository.ISysUserStationRepository;
import com.infore.siteManagement.repository.ITPlatformCustomerStationRepository;
import com.infore.siteManagement.service.IFilterService;
import com.infore.siteManagement.util.CookiesUtil;
import com.infore.siteManagement.util.ObjectMapperUtil;
import com.infore.siteManagement.util.ResultEntity;

@Service
public class FilterServiceImpl implements IFilterService {

	@Autowired
	private ISysUserStationRepository iSysUserStationRepository;
	@Autowired
	private IStationAndAppRepository iStationAndAppRepository;
	@Autowired
	private ITPlatformCustomerStationRepository platformCustomerStationRepository;
	@Autowired
	private IdentityManagement identityManagement;
	@Autowired
	private ObjectMapperUtil objectMapperUtil;
	@Autowired
	private IStationRepository iStationRepository;

	public List<Object> getFilterSql(HttpServletRequest request, YunlAppInfoParam params){
		List<Object> list = new ArrayList<Object>();
		StringBuilder sBuilder = new StringBuilder();
		StringBuilder leftJoin = new StringBuilder();
    	String roleId = null;
        String platfrom = null;
        String appCode = null;
        String userId = null;
        String admin = null;
		if(request != null) {
		     roleId = CookiesUtil.getCookieValue(request, "roleId");
		     platfrom = CookiesUtil.getCookieValue(request, "platformId");
		     appCode = CookiesUtil.getCookieValue(request, "appCode");
		     userId = CookiesUtil.getCookieValue(request, "userId");
		     admin = CookiesUtil.getCookieValue(request, "admin");
		}else {
		    roleId = params.getRoleId();
            platfrom = params.getPlatfrom();
            appCode = params.getAppCode();
            userId = params.getUserId();
            admin = params.getAdmin();
		}

		if (StringUtils.isNotBlank(appCode) && "operationma_app".equals(appCode)) {
			ResultEntity user = identityManagement.getUserById(userId);
			SysUser sysUser = objectMapperUtil.convertObject(user, SysUser.class);
			if ("5".equals(roleId)) {// 运维主管
				String cenId = sysUser.getOpCen().getId();
				cenId = " and T.OPCEN_ID = '" + cenId + "'";
				sBuilder.append(cenId);
			} else if ("6".equals(roleId)) {// 运维经理
				String opCompanyId = sysUser.getBranchOfc().getId();
				opCompanyId = " and T.OPER_COMPANY_ID = '" + opCompanyId + "'";
				sBuilder.append(opCompanyId);
			} else if ("1".equals(roleId)) {// 运维工程师
				String users = " and T.STATION_LEADER_ID = '" + userId + "'";
				sBuilder.append(users);
			} else if ("40282bab6dfb5526016dfb5cb11e0000".equals(roleId)
					|| "40282bab6e583e78016e583fd2da0000".equals(roleId)) {
				String left = " left join STATION_AND_APP app on T.station_id = app.STATION_ID";
				String and = " and app.APP_CODE = '" + appCode + "'";
				sBuilder.append(and);
				leftJoin.append(left);
			}
		}else {
			if (StringUtils.isBlank(admin) || "0".equals(admin)) {
				String left = " left join SYS_USER_STATION sus on T.station_id = sus.STATION_ID";
				String and = " and sus.user_id = '" + userId + "'";
				sBuilder.append(and);
				leftJoin.append(left);
			} else {
				// 如果是管理员则判断是那个平台下的或者系统下的管理员
				if (StringUtils.isNotBlank(platfrom)) {
					String left = " left join PLATFORM_CUSTOMER_STATION pcs on T.station_id = pcs.STATION_ID";
					String and = " and pcs.platform_id = '" + platfrom + "'";
					sBuilder.append(and);
					leftJoin.append(left);
				} else {
					String left = " left join STATION_AND_APP app on T.station_id = app.STATION_ID";
					String and = " and app.APP_CODE = '" + appCode + "'";
					sBuilder.append(and);
					leftJoin.append(left);
				}
			}
		}
		list.add(sBuilder);
		list.add(leftJoin);
		return list;
	}

	
	public List<String> getStationIdsByUserId(String userId) {
		List<String> stationIds = new ArrayList<String>();
		if (StringUtils.isBlank(userId)) {
			return stationIds;
		}
		List<SysUserStation> sysUserStations = iSysUserStationRepository.findByUserId(userId);
		stationIds = sysUserStations.stream().filter(f -> StringUtils.isNotBlank(f.getStationId()))
				.map(m -> m.getStationId()).collect(Collectors.toList());
		return stationIds;
	}

	List<String> OpeGetStationIds(String roleId,String userId,String admin ,String appCode) {
		List<String> ids = new ArrayList<String>();
		ResultEntity user = identityManagement.getUserById(userId);
		SysUser sysUser = objectMapperUtil.convertObject(user, SysUser.class);
		if ("5".equals(roleId)) {// 运维主管
			String cenId = sysUser.getOpCen().getId();
			ids = iStationRepository.queryIdByOpcenId(cenId);
		} else if ("6".equals(roleId)) {// 运维经理
			String opCompanyId = sysUser.getBranchOfc().getId();
			ids = iStationRepository.queryIdByCompanyId(opCompanyId);
		} else if ("1".equals(roleId)) {// 运维工程师
			ids = iStationRepository.queryIdByLeaderId(userId);
		}else if ("40282bab6dfb5526016dfb5cb11e0000".equals(roleId) || "40282bab6e583e78016e583fd2da0000".equals(roleId)) {
			ids = iStationAndAppRepository.queryStationByAppCpde(appCode);
		}
		return ids;
	}

	public List<String> getStationIdByCookie(HttpServletRequest request) {
		List<String> list = new ArrayList<String>();
		String roleId = CookiesUtil.getCookieValue(request, "roleId");
		String platfrom = CookiesUtil.getCookieValue(request, "platformId");
		String appCode = CookiesUtil.getCookieValue(request, "appCode");
		String userId = CookiesUtil.getCookieValue(request, "userId");
		String admin = CookiesUtil.getCookieValue(request, "admin");
		if (StringUtils.isNotBlank(appCode) && "operationma_app".equals(appCode)) {
			list = OpeGetStationIds(roleId, userId, admin, appCode);
			return list;
			//运维平台
		} else {
			//国家水站平台
			// 判断是不是管理员，不是则根据userId筛选
			if (StringUtils.isBlank(admin) || "0".equals(admin)) {
				list = getStationIdsByUserId(userId);
			} else {
				// 如果是管理员则判断是那个平台下的或者系统下的管理员
				if (StringUtils.isNotBlank(platfrom)) {
					List<TPlatformCustomerStation> tPlatformCustomerStations = platformCustomerStationRepository
							.findByPlatformId(platfrom);
					list = tPlatformCustomerStations.stream().map(m -> m.getStationId()).collect(Collectors.toList());
				} else {
					List<StationAndApp> stationAndApps = iStationAndAppRepository.findByAppCode(appCode);
					list = stationAndApps.stream().map(m -> m.getStationId()).collect(Collectors.toList());
				}
			}
		}
		return list;
	}

	public List<String> getStationIdByCookie(String platfrom, String appCode, String userId, String admin) {
		List<String> list = new ArrayList<String>();
		// 判断是不是管理员，不是则根据userId筛选
		if (StringUtils.isBlank(admin) || "0".equals(admin)) {
			list = getStationIdsByUserId(userId);
		} else {
			// 如果是管理员则判断是那个平台下的或者系统下的管理员
			if (StringUtils.isNotBlank(platfrom)) {
				List<TPlatformCustomerStation> tPlatformCustomerStations = platformCustomerStationRepository
						.findByPlatformId(platfrom);
				list = tPlatformCustomerStations.stream().map(m -> m.getStationId()).collect(Collectors.toList());
			} else {
				List<StationAndApp> stationAndApps = iStationAndAppRepository.findByAppCode(appCode);
				list = stationAndApps.stream().map(m -> m.getStationId()).collect(Collectors.toList());
			}
		}
		return list;
	}

}
